<template>
  <div class="task-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>My Tasks</h3>
          <div class="actions">
            <el-select v-model="priorityFilter" placeholder="Priority Filter" clearable style="width: 120px; margin-right: 10px;">
              <el-option label="High" value="High" />
              <el-option label="Medium" value="Medium" />
              <el-option label="Low" value="Low" />
            </el-select>
            <el-input
                v-model="searchQuery"
                placeholder="Search Tasks"
                prefix-icon="el-icon-search"
                clearable
                class="search-input"
                @input="handleSearch"
            />
          </div>
        </div>
      </template>


      <el-table
          :data="filteredTasks"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="title" label="Task Title" min-width="150" />
        <el-table-column prop="supervisorName" label="Supervisor" width="120" />
        <el-table-column prop="priority" label="Priority" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ scope.row.priority || 'Medium' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="Start Time" width="160" />
        <el-table-column prop="endTime" label="End Time" width="160" />
        <el-table-column label="Actions" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewTaskDetails(scope.row)">
              <el-icon><View /></el-icon>Details
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty-data">
            <el-empty description="No tasks assigned to you" :image-size="120">
              <template #description>
                <p>There are currently no tasks assigned to you.</p>
                <p class="sub-text">Tasks will be assigned by supervisors, please wait patiently.</p>
              </template>
            </el-empty>
          </div>
        </template>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalTasks"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Task details dialog -->
    <el-dialog
        v-model="detailsDialogVisible"
        title="Task Details"
        width="60%"
        destroy-on-close
    >
      <el-descriptions
          v-if="currentTask"
          :column="2"
          border
      >
        <el-descriptions-item label="Task Title">{{ currentTask.title }}</el-descriptions-item>
        <el-descriptions-item label="Task Status">
          <el-tag :type="getStatusType(currentTask.status)">
            {{ currentTask.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Supervisor">{{ currentTask.supervisorName }}</el-descriptions-item>
        <el-descriptions-item label="Priority">
          <el-tag :type="getPriorityType(currentTask.priority)">
            {{ currentTask.priority || 'Medium' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Start Time">{{ currentTask.startTime || 'Not set' }}</el-descriptions-item>
        <el-descriptions-item label="End Time">{{ currentTask.endTime || 'Not set' }}</el-descriptions-item>
        <el-descriptions-item label="Create Time">{{ currentTask.createTime }}</el-descriptions-item>
        <el-descriptions-item label="Update Time">{{ currentTask.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="Task Description" :span="2">
          <div class="task-description">{{ currentTask.description || 'No description' }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 添加文件上传区域 -->
      <div class="file-upload-section">
        <h3>Submit File</h3>
        <el-upload
            class="upload-demo"
            :action="`/api/user/tasks/${currentTask?.id}/submit`"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
        >
          <el-button type="primary">Click to Upload</el-button>
          <template #tip>
            <div class="el-upload__tip">
              Supports any type of file, up to 50MB in size.
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 添加已提交文件列表 -->
      <div v-if="submissions.length > 0" class="submission-list">
        <h3>Submitted Files</h3>
        <el-table :data="submissions" border style="width: 100%">
          <el-table-column prop="originalFilename" label="Filename" min-width="200" />
          <el-table-column prop="fileSize" label="Size" width="120">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="submissionTime" label="Submission Time" width="160" />
          <el-table-column label="Actions" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="downloadSubmission(scope.row)">
                Download
              </el-button>
              <el-button type="danger" size="small" @click="deleteSubmission(scope.row)">
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { View, Edit, Upload, Check, Close } from '@element-plus/icons-vue';
import { useUserStore } from '../../stores/user';
import { 
  Task, getStudentTasks, getTasksByStatus, getMyTaskDetail,
  updateTaskStatus as updateTaskStatusApi
} from '../../api/task';
import { 
  TaskSubmission, submitTaskFile, getTaskSubmissions, 
  deleteSubmission as apiDeleteSubmission 
} from '../../api/task';

// Data state
const tasks = ref<Task[]>([]);
const loading = ref<boolean>(false);
const searchQuery = ref<string>('');
const activeTab = ref<string>('all');
const priorityFilter = ref<string>(''); // Priority filter

// Pagination settings
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const totalTasks = ref<number>(0);

// Task details
const detailsDialogVisible = ref<boolean>(false);
const currentTask = ref<Task | null>(null);
const submissions = ref<any[]>([]);

// Add file upload related
const uploadHeaders = reactive({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
});

// Add user store to get the current user ID
const userStore = useUserStore();

// Filter tasks
const filteredTasks = computed(() => {
  // First make sure to only show tasks assigned to the current user
  let result = tasks.value.filter(task => task.assigneeId === userStore.user.id);

  // Priority filter
  if (priorityFilter.value) {
    result = result.filter(task => task.priority === priorityFilter.value);
  }

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(task =>
        task.title.toLowerCase().includes(query) ||
        (task.description && task.description.toLowerCase().includes(query))
    );
  }

  // Sort by priority and due date
  result = [...result].sort((a, b) => {
    // First sort by priority (High > Medium > Low)
    const priorityOrder = { 'High': 0, 'Medium': 1, 'Low': 2 }; // High, Medium, Low
    const priorityA = priorityOrder[a.priority || 'Medium']; // Medium
    const priorityB = priorityOrder[b.priority || 'Medium']; // Medium

    if (priorityA !== priorityB) {
      return priorityA - priorityB;
    }

    // If the priority is the same, sort by due date (closest first)
    if (a.endTime && b.endTime) {
      return new Date(a.endTime).getTime() - new Date(b.endTime).getTime();
    }

    // If there is no due date, put it at the end
    if (!a.endTime && b.endTime) return 1;
    if (a.endTime && !b.endTime) return -1;

    return 0;
  });

  // Pagination
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  totalTasks.value = result.length;
  return result.slice(start, end);
});

// Initialize data
onMounted(() => {
  fetchTasks();
});

// Get tasks
const fetchTasks = async () => {
  loading.value = true;
  try {
    let data;
    if (activeTab.value === 'all') {
      data = await getStudentTasks(userStore.user.id);
    } else {
      data = await getTasksByStatus(userStore.user.id, activeTab.value);
    }
    
    // Check and automatically update status of expired tasks
    if (data && data.length > 0) {
      data.forEach(task => {
        if (task.endTime && task.status !== 'Completed') {
          const endDate = new Date(task.endTime);
          const now = new Date();
          if (endDate < now) {
            // Task has expired, automatically update status to Completed
            updateTaskStatus(task.id, 'Completed');
            task.status = 'Completed';
          }
        }
      });
    }
    
    tasks.value = data || [];
    totalTasks.value = tasks.value.length;
  } catch (error) {
    console.error('Failed to retrieve task data:', error);
    ElMessage.error('Failed to retrieve task data');
  } finally {
    loading.value = false;
  }
};

// View task details
const viewTaskDetails = async (task: Task) => {
  // Reset file list to avoid displaying files from the previous task
  submissions.value = [];

  currentTask.value = task;
  detailsDialogVisible.value = true;

  // Get task submission records
  try {
    const result = await getTaskSubmissions(task.id);
    submissions.value = result;
  } catch (error) {
    console.error('Failed to retrieve task submission records:', error);
    ElMessage.error('Failed to retrieve task submission records');
  }
};

// Handle search
const handleSearch = () => {
  currentPage.value = 1;
};

// Handle tab switch
const handleTabClick = () => {
  currentPage.value = 1;
  fetchTasks();
};

// Handle page number change
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// Handle page size change
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// Helper functions
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (status) {
    case 'Draft': return 'primary'; // Draft
    case 'Midterm': return 'warning'; // Midterm
    case 'Final': return 'success'; // Final Draft
    default: return 'primary';
  }
};

const getPriorityType = (priority: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (priority) {
    case 'High': return 'danger'; // High
    case 'Medium': return 'warning'; // Medium
    case 'Low': return 'success'; // Low
    default: return 'warning';
  }
};

// Delete submission record
const deleteSubmission = async (submission: any) => {
  try {
    await apiDeleteSubmission(submission.id);

    // Update submission list
    submissions.value = submissions.value.filter(s => s.id !== submission.id);

    ElMessage.success('Submission record deleted');
  } catch (error) {
    console.error('Failed to delete submission record:', error);
    ElMessage.error('Failed to delete submission record');
  }
};

// Handle file validation before upload
const beforeUpload = (file: File) => {
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isLt50M) {
    ElMessage.error('File size cannot exceed 50MB!');
    return false;
  }

  return true;
};

// Handle successful upload
const handleUploadSuccess = async (response: any, file: any) => {
  ElMessage.success('File uploaded successfully, task has been submitted and is waiting for supervisor review');

  // Add to submission list
  submissions.value.push(response);

  // Re-get task details to get the latest status
  try {
    if (currentTask.value) {
      const updatedTask = await getTaskSubmissions(currentTask.value.id);

      // Update local task and current task
      currentTask.value = updatedTask[0];

      // Update task list
      const index = tasks.value.findIndex(t => t.id === updatedTask[0].id);
      if (index !== -1) {
        tasks.value[index] = updatedTask[0];
      }
    }
  } catch (error) {
    console.error('Failed to retrieve updated task details:', error);
  }
};

// Handle failed upload
const handleUploadError = (error: any) => {
  console.error('Upload failed:', error);
  ElMessage.error('File upload failed');
};

// Download submission file
const downloadSubmission = (submission: any) => {
  try {
    console.log('Starting to download file:', submission);

    // Get authorization token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('Authorization expired, please log in again');
      return;
    }
    
    // Show downloading tip
    const loadingInstance = ElLoading.service({
      lock: true,
      text: 'Preparing to download file...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // Single reliable method using Fetch API with proper headers
    fetch(`/api/user/submissions/${submission.id}/download`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => {
      // Close loading animation
      loadingInstance.close();
      
      if (!response.ok) {
        if (response.status === 404) {
          throw new Error('File does not exist or has been deleted');
        } else if (response.status === 403) {
          throw new Error('You do not have permission to download this file');
        } else if (response.status === 401) {
          throw new Error('Authorization expired, please log in again');
        } else {
          throw new Error(`Download failed: ${response.status}`);
        }
      }
      
      return response.blob();
    })
    .then(blob => {
      // Create download link for the blob
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = submission.originalFilename;
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
      
      ElMessage.success('File downloaded successfully');
    })
    .catch(error => {
      loadingInstance.close();
      console.error('Failed to download file:', error);
      
      // Show user-friendly error message
      ElMessageBox.alert(
        `Failed to download file "${submission.originalFilename}": ${error.message}`, 
        'Download Error', 
        {
          confirmButtonText: 'OK',
          type: 'error'
        }
      );
    });
  } catch (error) {
    console.error('Download file operation failed:', error);
    ElMessage.error('Failed to download file');
  }
};

// Format file size
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / 1024 / 1024).toFixed(2) + ' MB';
  }
};

// Add task status update function
const updateTaskStatus = async (taskId, status) => {
  try {
    await updateTaskStatusApi(taskId, { status: status });
    console.log(`Task ${taskId} status updated to ${status}`);
  } catch (error) {
    console.error(`Failed to update task ${taskId} status:`, error);
  }
};

// Refresh task details
const refreshTaskDetails = async () => {
  if (!currentTask.value) return;

  try {
    if (currentTask.value) {
      const updatedTask = await getMyTaskDetail(currentTask.value.id);

      // Update local task and current task
      currentTask.value = updatedTask;

      // Update task list
      const index = tasks.value.findIndex(t => t.id === updatedTask.id);
      if (index !== -1) {
        tasks.value[index] = updatedTask;
      }
    }
  } catch (error) {
    console.error('Failed to refresh task details:', error);
    ElMessage.error('Failed to refresh task details');
  }
};
</script>
<style scoped>
.task-list {
  padding: 10px;
  height: calc(100vh - 60px); /* Set height to viewport height minus top navigation bar height */
  overflow-y: auto; /* Add vertical scrollbar */
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.task-description {
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

/* Added styles */
.file-upload-section,
.submission-list {
  margin-top: 20px;
}

h3 {
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}
</style> 